<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Model;

class Cates extends Model
{

    protected $table = 'cates';

    protected $fillable = [
        'id','name','created_at','updated_at','pid','pitch','avatar'
    ];
    protected $casts = ['pitch'=>'array'];


    /**
     * 获取给定pid下的所有类目
     * @param int $pid 父级ID
     * @return array
     */
    protected function categories(int $pid){
        $lists = $this->select(['id','name','pid','pitch','avatar'])->where('pitch','like','%'.$pid.'%')->orderBy('created_at','asc')->get()->toArray();
        foreach ($lists as $key=>&$item){
            $item['label'] = $item['name'];
            $item['value'] = $item['id'];
        }
        return $this->listToTree($lists, 'id', 'pid', 'children', $pid);
    }


    /**
     * 把返回的数据集转换成Tree
     * @param $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     */
    public function listToTree($list, $pk='id', $pid='pid', $child='children', $root=0){
        // 创建Tree
        $tree = [];
        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
        return $tree;
    }


    /**
     * 获取给定pid下的所有类目
     * @param int $pid 父级ID
     * @return array
     */
    protected function wapCategories(int $pid){
        $lists = $this->select(['id','name','pid',])->where('pitch','like','%'.$pid.'%')->orderBy('created_at','asc')->get()->toArray();
        $parant = [];
        $child = [];
        $newLists = [];
        foreach ($lists as $key=>$item){
            if($item['pid'] == $pid){
                $parant[] = $item;
            }else{
                $child[] = $item;
            }
        }
        foreach ($parant as $ke=>$it){
            $newLists[] = $it;
            foreach ($child as $k=>&$m){
                if($m['pid'] == $it['id']){
                    $m['id'] = $m['pid'].'-'.$m['id'];
                    $m['name'] = $it['name'].'->'.$m['name'];
                    $newLists[] = $m;
                }
            }
        }
        return $newLists;
    }

}
